//通过vue-router插件实现路由配置
import { createRouter, createWebHashHistory } from 'vue-router';
import { constantRoute } from './routers';
import { parseJwt } from '@/utils/token';
import { adminRoute } from './admin';
import { studentRoute } from './student';

// 日志路由配置情况
console.log('路由初始化');
console.log('Admin routes:', adminRoute);
console.log('Student routes:', studentRoute);
console.log('Constant routes:', constantRoute);
console.log('Admin routes count:', Array.isArray(adminRoute) ? adminRoute.length : 'Not an array');
console.log('Student routes count:', Array.isArray(studentRoute) ? studentRoute.length : 'Not an array');

// 使用constantRoute作为路由配置
const routes = constantRoute;
const router = createRouter({
    //路由模式hash
    history: createWebHashHistory(),
    //@ts-ignore
    routes,
    //滚动行为
    scrollBehavior() {
        return {
            left: 0,
            top: 0
        }
    }
});

// 检查路由初始化
console.log('Router initialized with routes:', router.getRoutes().length);
console.log('Router routes:', router.getRoutes().map(r => r.path));

// 全局前置守卫
router.beforeEach((to, from, next) => {
    // 如果是根路径，直接重定向到登录页
    if (to.path === '/') {
        return next('/login');
    }
    
    // 如果用户正在访问登录页或注册页，直接放行
    if (to.path === '/login' || to.path === '/register' || to.path === '/forget') {
        return next();
    }

    const token = localStorage.getItem('TOKEN');
    console.log("token:", token);
    let userRole = '';

    if (token) {
        try {
            const claims = parseJwt(token);
            userRole = claims.role;
            console.log("User role:", userRole);
        } catch (error) {
            console.error('Failed to parse JWT:', error);
            return next('/login'); // 解析失败时跳转到登录页
        }

        // 如果没有 token 或者角色未知，跳转到登录页
        if (!['admin', 'student'].includes(userRole)) {
            return next('/login');
        }

        // 检查用户是否尝试访问与其角色不符的路径
        const path = to.path;
        if (userRole === 'admin' && path.startsWith('/student/')) {
            // 管理员尝试访问学生路径，重定向到第一个管理员菜单
            return next('/admin/class_manage');
        } else if (userRole === 'student' && path.startsWith('/admin/')) {
            // 学生尝试访问管理员路径，重定向到第一个学生菜单
            return next('/student/my_project');
        }

        // 对于刚登录的用户，重定向到对应的第一个菜单
        if (path === '/admin' || path === '/student') {
            if (userRole === 'admin') {
                return next('/admin/class_manage');
            } else if (userRole === 'student') {
                return next('/student/my_project');
            }
        }

        // 否则继续当前导航
        return next();
    } else {
        console.log("没带token");
        return next('/login'); // 没有 token 时跳转到登录页
    }
})
export default router;